extends CanvasLayer

@onready var health_bar = $HUD/HealthBar
@onready var experience_bar = $HUD/ExperienceBar
@onready var level_label = $HUD/LevelLabel
@onready var time_label = $HUD/TimeLabel
@onready var level_up_screen = $LevelUpScreen
@onready var upgrade_option_1 = $LevelUpScreen/VBoxContainer/UpgradeOption1
@onready var upgrade_option_2 = $LevelUpScreen/VBoxContainer/UpgradeOption2
@onready var upgrade_option_3 = $LevelUpScreen/VBoxContainer/UpgradeOption3

# 新增玩家状态显示
@onready var stats_container = $HUD/StatsContainer
@onready var armor_label = $HUD/StatsContainer/ArmorLabel
@onready var speed_label = $HUD/StatsContainer/SpeedLabel
@onready var crit_label = $HUD/StatsContainer/CritLabel
@onready var regen_label = $HUD/StatsContainer/RegenLabel

var game_time = 0.0
var player_node = null

# 升级选项池 (ID必须与Player.gd中的apply_upgrade匹配)
var upgrade_pool = [
	# 武器相关升级
	{"id": "add_knife", "text": "获得新飞刀", "rarity": "common", "type": "weapon"},
	{"id": "upgrade_knife_damage", "text": "飞刀伤害 +5", "rarity": "common", "type": "weapon"},
	{"id": "upgrade_knife_speed", "text": "飞刀频率 +10%", "rarity": "common", "type": "weapon"},
	{"id": "upgrade_knife_range", "text": "飞刀范围 +50", "rarity": "uncommon", "type": "weapon"},
	{"id": "add_fire_staff", "text": "获得火焰法杖", "rarity": "rare", "type": "weapon"},
	{"id": "add_ice_wand", "text": "获得冰霜魔杖", "rarity": "rare", "type": "weapon"},
	{"id": "add_lightning_chain", "text": "获得闪电链", "rarity": "rare", "type": "weapon"},
	{"id": "add_spinning_axe", "text": "获得旋转斧头", "rarity": "rare", "type": "weapon"},
	
	# 属性相关升级
	{"id": "increase_health", "text": "最大生命 +20", "rarity": "common", "type": "stat"},
	{"id": "increase_speed", "text": "移动速度 +20", "rarity": "common", "type": "stat"},
	{"id": "increase_armor", "text": "护甲值 +2", "rarity": "uncommon", "type": "stat"},
	{"id": "increase_pickup_range", "text": "拾取范围 +20%", "rarity": "common", "type": "stat"},
	{"id": "increase_health_regen", "text": "生命恢复 +1/秒", "rarity": "uncommon", "type": "stat"},
	{"id": "increase_crit_chance", "text": "暴击几率 +5%", "rarity": "uncommon", "type": "stat"},
	{"id": "increase_crit_damage", "text": "暴击伤害 +50%", "rarity": "rare", "type": "stat"},
	{"id": "increase_exp_gain", "text": "经验获取 +10%", "rarity": "uncommon", "type": "stat"},
	{"id": "increase_dodge", "text": "闪避几率 +5%", "rarity": "rare", "type": "stat"}
]

# 稀有度权重
var rarity_weights = {
	"common": 70,
	"uncommon": 25,
	"rare": 5
}

# 当前升级选择
var current_upgrade_choices = []

# 玩家等级对应的稀有度概率调整
var level_rarity_adjustments = {
	5: {"common": 60, "uncommon": 30, "rare": 10},
	10: {"common": 50, "uncommon": 35, "rare": 15},
	15: {"common": 40, "uncommon": 40, "rare": 20},
	20: {"common": 30, "uncommon": 45, "rare": 25}
}

func _ready():
	level_up_screen.hide() # 开始时隐藏升级界面
	
	# 查找玩家节点
	player_node = get_tree().get_first_node_in_group("player")
	if player_node:
		# 连接玩家信号到UI更新函数
		player_node.connect("health_changed", _on_player_health_changed)
		player_node.connect("experience_changed", _on_player_experience_changed)
		player_node.connect("leveled_up", _on_player_leveled_up)
		player_node.connect("player_stats_changed", _on_player_stats_changed)
		
		# 初始UI设置
		_on_player_health_changed(player_node.current_health, player_node.max_health)
		_on_player_experience_changed(player_node.experience, player_node.experience_needed, player_node.level)
	else:
		print("ERROR: UI couldn't find player node!")

	# 连接升级按钮
	upgrade_option_1.connect("pressed", _on_upgrade_selected.bind(0))
	upgrade_option_2.connect("pressed", _on_upgrade_selected.bind(1))
	upgrade_option_3.connect("pressed", _on_upgrade_selected.bind(2))
	
	# 初始化状态显示
	if stats_container:
		stats_container.hide() # 默认隐藏，可以通过按键切换显示

func _process(delta):
	if not get_tree().paused: # 只在游戏未暂停时更新时间
		game_time += delta
		# 格式化时间为MM:SS
		var minutes = int(game_time / 60)
		var seconds = int(game_time) % 60
		time_label.text = "Time: %02d:%02d" % [minutes, seconds]

func _on_player_health_changed(new_health, max_health):
	health_bar.max_value = max_health
	health_bar.value = new_health

func _on_player_experience_changed(new_xp, needed_xp, current_level):
	experience_bar.max_value = needed_xp
	experience_bar.value = new_xp
	level_label.text = "Level: " + str(current_level)

func _on_player_stats_changed(stats_dict):
	# 更新状态显示
	if armor_label:
		armor_label.text = "护甲: " + str(stats_dict.armor)
	if speed_label:
		speed_label.text = "速度: " + str(stats_dict.speed)
	if crit_label:
		crit_label.text = "暴击: " + str(int(stats_dict.crit_chance * 100)) + "%"
	if regen_label:
		regen_label.text = "恢复: " + str(stats_dict.health_regen) + "/秒"

func _on_player_leveled_up(current_level):
	# 生成3个独特的升级选项
	current_upgrade_choices.clear()
	
	# 根据玩家等级调整稀有度权重
	var current_weights = rarity_weights.duplicate()
	for level_threshold in level_rarity_adjustments.keys():
		if current_level >= level_threshold:
			current_weights = level_rarity_adjustments[level_threshold]
	
	# 按类型分类升级选项
	var weapon_upgrades = []
	var stat_upgrades = []
	
	for upgrade in upgrade_pool:
		if upgrade.type == "weapon":
			weapon_upgrades.append(upgrade)
		else:
			stat_upgrades.append(upgrade)
	
	# 确保至少有一个武器升级和一个属性升级
	var selected_weapon = _select_weighted_upgrade(weapon_upgrades, current_weights)
	var selected_stat = _select_weighted_upgrade(stat_upgrades, current_weights)
	
	current_upgrade_choices.append(selected_weapon)
	current_upgrade_choices.append(selected_stat)
	
	# 第三个选项可以是任意类型
	var remaining_upgrades = upgrade_pool.duplicate()
	remaining_upgrades.erase(selected_weapon)
	remaining_upgrades.erase(selected_stat)
	
	if remaining_upgrades.size() > 0:
		current_upgrade_choices.append(_select_weighted_upgrade(remaining_upgrades, current_weights))
	
	# 更新按钮文本
	if current_upgrade_choices.size() > 0:
		upgrade_option_1.text = current_upgrade_choices[0].text
		upgrade_option_1.show()
	else:
		upgrade_option_1.hide()
	
	if current_upgrade_choices.size() > 1:
		upgrade_option_2.text = current_upgrade_choices[1].text
		upgrade_option_2.show()
	else:
		upgrade_option_2.hide()
	
	if current_upgrade_choices.size() > 2:
		upgrade_option_3.text = current_upgrade_choices[2].text
		upgrade_option_3.show()
	else:
		upgrade_option_3.hide()
	
	# 显示升级界面
	level_up_screen.show()

# 根据权重选择升级选项
func _select_weighted_upgrade(upgrades, weights):
	if upgrades.size() == 0:
		return null
	
	# 计算总权重
	var total_weight = 0
	var weighted_upgrades = []
	
	for upgrade in upgrades:
		var rarity = upgrade.rarity
		var weight = weights[rarity]
		total_weight += weight
		weighted_upgrades.append({"upgrade": upgrade, "weight": weight})
	
	# 随机选择
	var random_value = randf() * total_weight
	var current_weight = 0
	
	for weighted_upgrade in weighted_upgrades:
		current_weight += weighted_upgrade.weight
		if random_value <= current_weight:
			return weighted_upgrade.upgrade
	
	# 如果出现问题，返回第一个
	return upgrades[0]

func _on_upgrade_selected(choice_index):
	if choice_index < current_upgrade_choices.size():
		var selected_upgrade = current_upgrade_choices[choice_index]
		print("UI: Upgrade selected - ", selected_upgrade.text)
		# 告诉玩家应用选择的升级
		if player_node:
			player_node.apply_upgrade(selected_upgrade.id)
		
		# 隐藏升级界面
		level_up_screen.hide()
		# 游戏在Player.gd的apply_upgrade函数中取消暂停
	else:
		print("ERROR: Invalid upgrade choice index")
		# 安全措施：如果出现问题，隐藏界面并取消暂停
		level_up_screen.hide()
		if player_node: get_tree().paused = false

# 切换状态显示
func toggle_stats_display():
	if stats_container:
		stats_container.visible = !stats_container.visible

# 显示游戏结束界面
func show_game_over_screen(score, time_survived):
	# 实现游戏结束界面
	pass
